﻿
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section css{

    <link href="/Statics/adminlte/plugins/wizard/css/jquery.steps.css" rel="stylesheet" />
}
<div id="wizard" style="padding-top:10px">
    <h1>第一步: 商品基本属性</h1>
    <div style="padding:20px 10px">
        <div class="form-group row">
            <label for="Name" class="col-sm-2 col-form-label">商品名称:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="ProductTitle" name="ProductTitle" placeholder="请输入商品名称">
            </div>
        </div>
        <div class="form-group row">
            <label class="col-sm-2 col-form-label">商品品牌:</label>
            <div class="col-sm-10">
                <select id="brand" class="form-control" style="font-size:14px;">
                </select>
            </div>

        </div>
        <div class="form-group row">
            <label for="Name" class="col-sm-2 col-form-label">商品价格:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="ProductPrice" name="ProductPrice" placeholder="请输入商品价格">
            </div>
        </div>
        <div class="form-group row">
            <label for="Name" class="col-sm-2 col-form-label">商品库存:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="ProductStock" name="ProductStock" placeholder="请输入商品库存">
            </div>
        </div>
    </div>

    <h1>第二步: 商品图片</h1>
    <div style="padding:20px 10px">
        <div class="form-group row">
            <label for="file" class="col-sm-2 col-form-label">商品主图:</label>
            <div class="col-sm-10">
                <input type="file" id="ProductMainImg">
            </div>
        </div>
        <div class="form-group row">
            <label for="file" class="col-sm-2 col-form-label">商品轮播图:</label>
            <div class="col-sm-10">
                <input type="file" id="ProductSlideImgs" multiple>
            </div>
        </div>
        <div class="form-group row">
            <label for="file" class="col-sm-2 col-form-label">商品详情:</label>
            <div class="col-sm-10">
                <input type="file" id="ProductDetail" multiple>
            </div>
        </div>
    </div>

    <h1>第三步: 商品属性、SKU</h1>
    <div style="padding:20px 10px">
        <div class="form-group row" style="margin-bottom:20px">
            <label class="col-sm-1 col-form-label">商品类别:</label>
            <div class="col-sm-10">
                <div class="row">
                    <div class="col-sm-4">
                        <div class="row">
                            <span class="col-sm-4 col-form-label">一级分类</span>
                            <select id="category1" class="form-control col-sm-6  select2 " style="font-size:14px;width:60%">
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <div class="row">
                            <span class="col-sm-4 col-form-label">二级分类</span>
                            <select id="category2" class="col-sm-6 form-control  select2 " style="font-size:14px;width:60%">
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <div class="row">
                            <span class="col-sm-4 col-form-label">三级分类</span>
                            <select id="category3" class="col-sm-6 form-control  select2 " style="font-size:14px;width:60%">
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group row" style="margin-bottom:20px">
            <label class="col-sm-1 col-form-label">商品规格(SKU):</label>
            <div class="col-sm-10">
                <div id="skus" style="padding:20px;margin-bottom:15px;background-color:rgb(244,246,249);border:1px solid #eee;border-radius:5px">

                </div>
                <div>
                    <table id="sku-table" class="table table-bordered">
                        <thead>
                            <tr>
                                <th>价格</th>
                                <th>库存</th>
                                <th>SKU编号</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
                <div class="row">
                    <div class="col-sm-2">
                        <button type="button" class="btn btn-primary" onclick="createSkuCollections()">生成sku组合</button>
                    </div>
                    <div class="col-sm-2">
                        <button type="button" class="btn btn-primary" onclick="autoWritePrice()">同步价格</button>
                    </div>
                    <div class="col-sm-2">
                        <button type="button" class="btn btn-primary" onclick="autoWriteStock()">同步库存</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group row" style="margin-bottom:20px">
            <label class="col-sm-1 col-form-label">商品参数:</label>
            <div id="attrs" style="padding:20px;margin-bottom:15px;background-color:rgb(244,246,249);border:1px solid #eee;border-radius:5px">

            </div>
        </div>

    </div>
</div>
@section js{

    <script src="/Statics/adminlte/plugins/wizard/js/jquery.steps.js"></script>
    <script>
        //侯海啸
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
        var ProductMainImg = [], ProductSlideImgs = [], ProductDetail = [], ProductCategoryID
        
        $("#wizard").steps({
            labels: {
                next: "下一步",
                previous: "上一步",
                finish: "完成"
            },
            onFinished: function () {

                var product = {}
                var productObj = {}
                productObj.ID = $.getUrlParam("id")

                productObj.productTitle = $("#ProductTitle").val()
                productObj.price = $("#ProductPrice").val()
                productObj.stock = $("#ProductStock").val()
                productObj.ProductBrandID = $("#brand").val()
                //JSON.stringify:将数组或者js对象转化成json字符串
                productObj.ProductMainImg = JSON.stringify(ProductMainImg);
                productObj.ProductSlideImgs = JSON.stringify(ProductSlideImgs);
                productObj.ProductDetail = JSON.stringify(ProductDetail);
                productObj.ProductCategoryID = ProductCategoryID;
                productObj.ProductCategoryPath = JSON.stringify([
                    $("#category1").val(),
                    $("#category2").val(),
                    $("#category3").val()
                ])
                productObj.ProductSkuValues = JSON.stringify(skuArrays)

                product.Product = productObj;
                skuDatas = []
                //侯海啸
                $("#sku-table tbody tr").each(function (index) {
                    var sku = {}
                    sku.ProductSku1 = JSON.stringify(results[index])
                    sku.Price = $(this).find("input.price").val()
                    sku.Stock = $(this).find("input.stock").val()
                    sku.SkuNum = $(this).find("input.sku-num").val()
                    skuDatas.push(sku)
                })
                product.Skus = skuDatas
                attrDatas = []
                $("#attrs div.attr").each(function () {
                    var attr = {}
                    attr.AttrName = $(this).find("span.attr-name").text()
                    var enterType = $(this).attr("enter-type")
                    var attrValue;
                    if (enterType == "1") {
                        attrValue = $(this).find("input").val()
                    } else {
                        attrValue = $(this).find("select").val()
                    }
                    attr.AttrValue = attrValue
                    attrDatas.push({ productAttrs: JSON.stringify(attr) })
                })
                product.Attrs = attrDatas


                $.ajax({
                    url: "/Product/Update",
                    type: "POST",
                    dataType: "json",
                    data: JSON.stringify(product),
                    contentType: "application/json;charset=utf-8",
                    success: function (result) {
                        if (result.state) {
                            toastr.success('修改成功')
                        } else {
                            toastr.error('修改失败')
                        }
                    },

                })
            }
        });


        $('#ProductMainImg').on('fileuploaded', function (event, data, previewId, index) {
            ProductMainImg.push(data.response[0])
        });

        $('#ProductMainImg').on('change', function (event) {
            ProductMainImg = []
        });
        $('#ProductSlideImgs').on('fileuploaded', function (event, data, previewId, index) {
            ProductSlideImgs.push(data.response[0])
        });
        $('#ProductSlideImgs').on('change', function (event) {
            ProductSlideImgs = []
        });
        $('#ProductDetail').on('fileuploaded', function (event, data, previewId, index) {
            ProductDetail.push(data.response[0])
        });
        $('#ProductDetail').on('change', function (event) {
            ProductDetail = []
        });
        //自动填写库存
        function autoWriteStock() {
            //侯海啸
            var stock = $("#sku-table tbody tr:eq(0) input.stock").val()
            $("#sku-table tbody input.stock").val(stock)
        }
        //自动填写价格
        function autoWritePrice() {
            var price = $("#sku-table tbody tr:eq(0) input.price").val()
            $("#sku-table tbody input.price").val(price)
        }
        var skuArrays = [];
        results = [];
        result = [];
        //生成排列后数组
        function doExchange(arr, depth) {
            //侯海啸
            for (var i = 0; i < arr[depth].length; i++) {
                result[depth] = arr[depth][i]
                if (depth != arr.length - 1) {
                    doExchange(arr, depth + 1)
                } else {
                    results.push(result.slice())
                }
            }
        }
        //生成表格
        function createSkuCollections() {
            results = [];
            result = [];
            newSkuArrays = [];
            skuArrays.map(function (v) {
                newSkuArrays.push(v.values)
            })
            console.log()
            //侯海啸
            doExchange(newSkuArrays, 0)

            //表头
            $("#sku-table thead tr").empty();

            results[0].map(function (v) {
                $("#sku-table thead tr").append("<th>" + v.name + "</th>");
            })
            $("#sku-table thead tr").append("<th>价格</th>");
            $("#sku-table thead tr").append("<th>库存</th>");
            $("#sku-table thead tr").append("<th>SKU编号</th>");
            $("#sku-table tbody").empty();

            //数据
            results.map(function (v) {
                var html = "<tr>"
                v.map(function (_v) {
                    html += "<td>" + _v.value + "</td>"
                })
                html += "<td><input  class=\"price form-control\" type=\"text\"/></td>"
                html += "<td><input  class=\"stock form-control\" type=\"text\"/></td>"
                html += "<td><input class=\"sku-num form-control\"  type=\"text\"/></td>"
                html += "</tr>"
                $("#sku-table tbody").append(html);
            })




        }
        //填充三级联动
        function fillCategory(pid, $select) {
            //重复填充方法
            $.ajax({
                url: "../ProductCategory/GetByPID",
                type: "GET",
                async: false,
                data: { pid: pid },
                dataType: "json",
                success: function (data) {

                    $select.append("<option value=\"\">请选择</option>")

                    data.map(function (v) {
                        $select.append("<option value=\"" + v.ID + "\">" + v.Name + "</option>")
                    })
                }
            })
        }
        //手动录入规格
        function addSku(inputID, divID, skuName) {
            var skuValue = $("#" + inputID).val();
            var html = "";
            html += "<div class=\"icheck-primary d-inline sku\" style=\"padding-right:15px;\">";
            html += "<input id=\"sku-checkbox-" + skuValue + "\" onchange=\"addSkuToArray(this,'" + skuName + "','" + skuValue + "')\" type=\"checkbox\" />";
            html += "<label for=\"sku-checkbox-" + skuValue + "\" style=\"font-weight:normal\">" + skuValue + "</label>";
            $("#" + divID).append(html);
        }
        function addSku1(divID, skuName, skuValue) {
            var html = "";
            html += "<div class=\"icheck-primary d-inline sku\" style=\"padding-right:15px;\">";
            html += "<input id=\"sku-checkbox-" + skuValue + "\" onchange=\"addSkuToArray(this,'" + skuName + "','" + skuValue + "')\" type=\"checkbox\" />";
            html += "<label for=\"sku-checkbox-" + skuValue + "\" style=\"font-weight:normal\">" + skuValue + "</label>";
            $("#" + divID).append(html);
        }
        //选择checkbox添加到数组时判断
        function addSkuToArray(obj, skuName, skuValue) {
            //侯海啸
            var isChecked = $(obj).prop("checked");
            skuArrays.map(function (v) {

                if (skuName == v.name) {
                    console.log(v)
                    var pos = -1;
                    for (var i = 0; i < v.values.length; i++) {
                        if (v.values[i].value == skuValue) {
                            pos = i;
                            break;
                        }
                    }
                    if (isChecked) {
                        if (pos == -1) {
                            v.values.push({ name: skuName, value: skuValue })

                        }
                    } else {
                        if (pos != -1) {
                            v.values.splice(pos, 1);
                        }

                    }
                }
                console.log(skuArrays)
            })


        }
        //填充数据
        function init() {
            var id = $.getUrlParam("id")
            $.ajax({
                url: "/ProductBrand/GetAllByAddProduct",
                type: "GET",
                
                dataType: "json",
                success: function (data) {
                    $("#brand").append("<option value=\"\">请选择</option>")

                    data.map(function (v) {
                        $("#brand").append("<option value=\"" + v.ID + "\">" + v.BrandName + "</option>")
                    })
                }
            })
            $.ajax({
                url: "/Product/GetOne",
                type: "GET",
                data: { id: id },
                dataType: "json",
                
                success: function (data) {
                    //1初始化商品基本信息
                    var productObj = data.product
                    console.log(productObj)

                    $("#ProductTitle").val(productObj.ProductTitle)
                    $("#ProductPrice").val(productObj.Price)
                    $("#ProductStock").val(productObj.Stock)
                    $("#brand").val(productObj.ProductBrandID);
                    //2初始化商品主图、轮播图、详情
                    //eval():接收一个字符串类型参数，可以将字符串转换成数组或对象,eval("()")
                    var _ProductMainImg = eval("(" + productObj.ProductMainImg + " )")
                    var ProductMainImgTag = ["<img src='" + _ProductMainImg[0] + "' class=' file-preview-image' width=' 200'>"]
                    ProductMainImg.push(_ProductMainImg[0])

                    $('#ProductMainImg').fileinput({
                        language: 'zh', //设置语言
                        allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif'],//接收的文件后缀
                        showUpload: true, //是否显示上传按钮
                        browseClass: "btn btn-primary", //按钮样式
                        dropZoneEnabled: false,
                        uploadUrl: "/Img/Upload",
                        uploadAsync: true,//默认异步上传
                        uploadExtraData: { imgType: 'ProductMainImg' },//添加额外的参数:图片类型
                        initialPreview: ProductMainImgTag
                    });
                    var _ProductSlideImgs = eval("(" + productObj.ProductSlideImgs + ")")
                    var ProductSlideImgTag = []
                    _ProductSlideImgs.map(function (v) {
                        ProductSlideImgTag.push("<img src='" + v + "'class='file-preview-image'  width='200'>");
                        ProductSlideImgs.push(v)

                    })
                    $('#ProductSlideImgs').fileinput({
                        language: 'zh', //设置语言
                        allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif'],//接收的文件后缀
                        showUpload: true, //是否显示上传按钮
                        browseClass: "btn btn-primary", //按钮样式
                        dropZoneEnabled: true,
                        uploadUrl: "/Img/Upload",
                        uploadAsync: true,//默认异步上传
                        uploadExtraData: { imgType: 'ProductSlideImgs' },//添加额外的参数:图片类型
                        initialPreview: ProductSlideImgTag
                    });
                    var _ProductDetail = eval("(" + productObj.ProductDetail + ")")
                    var ProductDetailImgTag = []
                    _ProductDetail.map(function (v) {
                        ProductDetailImgTag.push("<img src='" + v + "'class= ' file-preview- image' width = '200' > ");
                        ProductDetail.push(v)

                    })
                    $('#ProductDetail').fileinput({
                        language: 'zh', //设置语言
                        allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif'],//接收的文件后缀
                        showUpload: true, //是否显示上传按钮
                        browseClass: "btn btn-primary", //按钮样式
                        dropZoneEnabled: true,
                        uploadUrl: "/Img/Upload",
                        uploadAsync: true,//默认异步上传
                        uploadExtraData: { imgType: 'ProductDetailImg' },//添加额外的参数:图片类型
                        initialPreview: ProductDetailImgTag
                    });
                    //3初始化商品分类
                    var productCategoryPath = eval("(" + productObj.ProductCategoryPath + ")")
                    console.log(productObj)
                    $("#category1").val(productCategoryPath[0])//设置-级分类
                    $("#category1").trigger("change");//触发一级分类下拉框change事件

                    $("#category2").val(productCategoryPath[1])//设置二级分类
                    $("#category2").trigger("change");//触发二级分类下拉框change事件

                    $("#category3").val(productCategoryPath[2])//设置三级级分类
                    $("#category3").trigger("change");//触发三级分类下拉框change事件
                    //初始化sku信息
                    $("#skus div.sku-list").each(function () {

                        var attrName = $(this).find("div.attr-name").text()
                        var enterType = $(this).attr("enter-type")
                        //手工录入
                        if (enterType == 1) {
                            eval("(" + productObj.ProductSkuValues + ")").find(function (v) {
                                if (attrName == v.name) {
                                    v.values.find(function (_v) {
                                        addSku1("sku-" + attrName + "-div", attrName, _v.value)

                                        var checkbox = $("#sku-checkbox-" + _v.value)
                                        checkbox.prop("checked", true);//设为选中
                                        checkbox.trigger("change")//触发change事件,将skuValue添加到skuArrays数组中

                                    })
                                }
                            })
                        }
                        //下拉选择
                        if (enterType == 2) {
                            $(this).find("div.sku").each(function () {

                                var checkbox = $(this).find("input[type='checkbox']")
                                var skuValue = checkbox.attr("sku-value")

                                eval("(" + productObj.ProductSkuValues + ")").find(function (v) {
                                    if (attrName == v.name) {
                                        v.values.find(function (_v) {
                                            if (_v.value == skuValue) {
                                                checkbox.prop("checked", true);//设为选中
                                                checkbox.trigger("change")// 触发change事件，将skuValue添加到skuArrays数组中


                                            }
                                        })
                                    }
                                })
                            })
                        } else {

                        }
                    })

            //4初始化sku表格信息
            //生成表头
            $("#sku-table thead tr").empty()

            eval("(" + data.skus[0].ProductSku1 + ")").map(function (v) {

                $("#sku-table thead tr").append("<th>" + v.name + "</th>")

            })
            $("#sku-table thead tr").append("<th>价格</th>")
            $("#sku-table thead tr").append("<th>库存</th>")
            $("#sku-table thead tr").append("<th>SKU编号</th>")
            //生成数据行
            $("#sku-table tbody").empty()
            data.skus.map(function (v) {
                var html = "<tr>"
                eval("(" + v.ProductSku1 + ")").map(function (_v) {
                    html += "<td>" + _v.value + "</td> "
                })
                html += "<td><input type=\"text\" class=\"price form-control\" value = \"" + v.Price + "\"/></td>"
                html += "<td><input type=\"text\" class=\"stock form-control\" value = \"" + v.Stock + "\" /></td>"
                html += "<td><input type=\"text\" class=\"sku-num form-control\" value = \"" + v.SkuNum + "\" /></td>"
                html += "</tr>"

                $("#sku-table tbody").append(html)
                results.push(eval("(" + v.ProductSku1 + ")"))

            })

            //5初始化属性信息
            $("#attrs div.attr").each(function () {
                var attrName = $(this).find("span.attr-name").text()
                var attrValue = null;
                //根据属性名称在data. attrs数组中进行查找并获取属性值
                data.attrs.find(function (v) {
                    var attr = eval("(" + v.ProductAttrs + ")")
                    if (attr.AttrName == attrName) {
                        attrValue = attr.AttrValue
                        return true
                    }
                })

                if (attrValue != null) {
                    var enterType = $(this).attr("enter-type")
                    if (enterType == "1") {
                        $(this).find("input").val(attrValue)
                    }
                    else {
                        $(this).find("select").val(attrValue)
                    }
                }

            })
        }
                })

            }

        $(function () {
            //侯海啸

            //三级联动
            fillCategory(0, $("#category1"));
            $("#category1").change(function () {
                $("#category2").empty()
                var pid = $(this).val()
                fillCategory(pid, $("#category2"));
            })
            $("#category2").change(function () {
                $("#category3").empty()
                var pid = $(this).val()
                fillCategory(pid, $("#category3"));
            })
            $("#category3").change(function () {
                console.log(results)
                var id = ProductCategoryID = $(this).val();
                $("#skus").empty();
                $("#sku-table thead tr").empty();
                $("#sku-table tbody").empty();
                $("#attrs").empty();
                //sku
                $.ajax({
                    url: "/ProductAttrKeySku/GetByCategoryID",
                    type: "GET",
                    data: { categoryID: id },
                    dataType: "json",
                    async: false,

                    success: function (data) {

                        console.log(data);
                        data.map(function (v) {
                            var sku = {};
                            sku.name = v.AttrName
                            sku.values = []
                            //侯海啸
                            var html = " <div style=\"padding-bottom:15px;\" class=\"sku-list\" enter-type=\" " + v.EnterType + "\">";
                            html += "<div style=\"padding-bottom:5px;\" class=\"attr-name\">" + v.AttrName + "</div>";
                            html += " <div>";
                            if (v.EnterType == 1) {
                                html += "<div class=\"row\" style=\"padding-bottom:5px;\">" +
                                    "<div class=\"col-sm-3\"><input type=\"text\" class=\"form-control\" id=\"sku-" + v.AttrName + "-input\"></div><div class=\"col-sm-3\"><button  onclick=\"addSku('sku-" + v.AttrName + "-input','sku-" + v.AttrName + "-div','" + v.AttrName + "')\" type=\"button\" class=\"btn btn-primary\">添加</button></div></div>";
                                html += "<div id=\"sku-" + v.AttrName + "-div\"></div>";
                                html += "</div>";

                            } else if (v.EnterType == 2) {

                                v.AttrValues.map(function (v_attrValue) {
                                    html += "<div class=\"icheck-primary d-inline sku\" style=\"padding-right:15px;\">";
                                    html += "<input sku-value=\"" + v_attrValue + "\" type=\"checkbox\" id=\"sku-checkbox-" + v_attrValue + "\" onchange=\"addSkuToArray(this,'" + v.AttrName + "','" + v_attrValue + "')\"/>";
                                    html += "<label for=\"sku-checkbox-" + v_attrValue + "\" style=\"font-weight:normal\">" + v_attrValue + "</label>";
                                    html += "</div>";
                                })

                            }


                            $("#skus").append(html);
                            skuArrays.push(sku)
                            console.log(skuArrays);
                        })
                    }
                })
                //attr
                $.ajax({
                    url: "/ProductAttrKey/GetWithAttrValuesByCategoryID",
                    type: "GET",
                    data: { categoryID: id },
                    dataType: "json",
                    async: false,
                    success: function (data) {

                        console.log(data);
                        data.map(function (v) {
                            var sku = {};
                            sku.name = v.AttrName
                            sku.values = []
                            //侯海啸
                            var html = " <div class=\"form-group row attr\" enter-type=\"" + v.EnterType + "\">" +
                                "<span class=\"col-sm-4 col-form-label attr-name\">" + v.AttrName + "</span>";
                            if (v.EnterType == 1) {
                                html += "<div class=\"col-sm-6\"><input type=\"text\" class=\"form-control\" id=\"sku-" + v.AttrName + "-input\" style=\"width:100%;\"></div>";
                                html += "<div id=\"sku-" + v.AttrName + "-div\"></div>";
                                html += "</div>";
                            } else if (v.EnterType == 2) {
                                html += "<select id=\"PID\" class=\"form-control col-sm-6\" style=\"font-size:14px;width:100%;\">" +
                                    "<option value=\"0\">请选择</option>";
                                v.AttrValues.map(function (v_attrValur) {
                                    html += "<option value=\"" + v_attrValur + "\">" + v_attrValur + "</option>";
                                })
                                html += "</select>";
                            }
                            html += "</div>"

                            $("#attrs").append(html);
                        })
                    }
                })
            })
            $("#upload").click(function () {
                var formData = new FormData();
                var files = $("#file")[0].files
                for (var i in files) {
                    formData.append("file", files[i])
                }
                formData.append("imgType", "ProductMainImg")
                $.ajax({
                    url: "/Img/Upload",
                    type: "POST",
                    dateType: "json",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (result) {
                        console.log(result)
                    },
                    error: function (result) {

                    }

                })
            })

            init();

        })
    </script>
}
